﻿#encoding: utf-8

require 'pexels'
require 'open-uri'

load 'tutem_utils.rb'

def new_pexels_client
    key = ENV['PEXELS_API_KEY']
    client = Pexels::Client.new(key)
    return client
end

def image_url_to_file url, fn
  open(fn, 'wb') do |file|
    file << open(url).read
  end
end

def get_daily_portrait

    day = Time.now.to_date
    page = day.month * 100 + day.day #数据这似乎更新，就是按日期做下标，共8000条数据

    today = Time.now.strftime("%Y-%m-%d")
    tomorrow = day.next_day.strftime("%Y-%m-%d")
    fn = 'DCC-BG-' + today + '.png'
    fm = 'DCC-BG-' + tomorrow + '.png'

    client = new_pexels_client
    curated = client.photos.curated(per_page:1, page: page)
    total_results = curated.total_results
    photos = curated.photos
    photo = photos[0]
    src = photo.src
    portrait = src['portrait']
    image_url_to_file portrait, fn
    image_url_to_file portrait, fm

end

def gen_more_pics

    client = new_pexels_client

    day = Date.new(2022,12,28)
    day_counts = 10

    idx = 1
    page = 1

    begin

      curated = client.photos.curated(per_page:80, page: page)
      total_results = curated.total_results
      photos = curated.photos

      photos.each do |photo|
        #photo = photos[0]

        fn = 'DCC-BG-' + day.to_s + '.png'
        puts "saving photo for #{day.to_s} as #{fn}..."

        src = photo.src
        portrait = src['portrait']
        image_url_to_file portrait, fn

        day = day.next_day

      end

      page += 1

    end while idx < day_counts
end
#gen_more_pics
